# 创建排片分析组件
<template>
  <div class="showing-analysis">
    <el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <span>排片分析</span>
          <div class="header-right">
            <el-radio-group v-model="analysisType" size="small">
              <el-radio-button label="count">场次分析</el-radio-button>
              <el-radio-button label="rate">占比分析</el-radio-button>
              <el-radio-button label="trend">趋势分析</el-radio-button>
            </el-radio-group>
            <el-button type="primary" size="small" @click="loadData">
              <el-icon><Refresh /></el-icon>刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 图表容器 -->
      <div class="chart-container" ref="chartRef"></div>
      
      <!-- 分析总结 -->
      <div class="analysis-summary">
        <h3>分析总结</h3>
        <div class="summary-content" v-if="tableData.length">
          <template v-if="analysisType === 'count'">
            <p>当前共有 {{ movieCount }} 部电影在映，总排片场次 {{ totalShowCount }} 场。其中：</p>
            <ul>
              <li>排片冠军《{{ topMovie?.movie_name }}》共 {{ topMovie?.show_count }} 场</li>
              <li>前三名电影排片占比达 {{ top3Concentration.toFixed(2) }}%，市场集中度{{ top3Concentration > 60 ? '较高' : '适中' }}</li>
              <li>排名前十的电影中，{{ getTop10Analysis() }}</li>
            </ul>
          </template>

          <template v-if="analysisType === 'rate'">
            <p>排片占比分析显示：</p>
            <ul>
              <li>头部电影《{{ topMovie?.movie_name }}》占据 {{ (topMovie?.show_count_rate * 100).toFixed(2) }}% 的市场份额</li>
              <li>前八大电影累计占据 {{ getTop8Proportion().toFixed(2) }}% 的排片量</li>
              <li>市场竞争格局{{ getMarketCompetition() }}</li>
            </ul>
          </template>

          <template v-if="analysisType === 'trend'">
            <p>排片趋势分析：</p>
            <ul>
              <li>{{ getTrendAnalysis() }}</li>
              <li>环比变化 {{ showCountGrowth > 0 ? '+' : '' }}{{ showCountGrowth.toFixed(2) }}%，{{ getGrowthComment() }}</li>
              <li>近期排片走势{{ getTrendComment() }}</li>
            </ul>
          </template>
        </div>
        <el-empty v-else description="暂无数据可供分析" />
      </div>
      
      <!-- 数据表格 -->
      <el-table
        :data="paginatedData"
        style="width: 100%; margin-top: 20px;"
        :height="300"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="movie_name" label="电影名称" min-width="120" />
        <el-table-column label="排片场次" min-width="100" sortable>
          <template #default="{ row }">
            {{ row.show_count }}
          </template>
        </el-table-column>
        <el-table-column label="排片占比" min-width="120" sortable>
          <template #default="{ row }">
            <el-progress 
              :percentage="row.show_count_rate * 100" 
              :format="(val) => val.toFixed(2) + '%'"
              :color="getProgressColor(row.show_count_rate)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="release_info" label="上映信息" min-width="120" />
        <el-table-column prop="updated_at" label="更新时间" min-width="160" />
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getMovies } from '@/api/movie'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const analysisType = ref('count')
const chartRef = ref(null)
const chart = ref(null)
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 计算总排片场次
const totalShowCount = computed(() => {
  return tableData.value.reduce((sum, movie) => sum + movie.show_count, 0)
})

// 计算电影数量
const movieCount = computed(() => tableData.value.length)

// 获取排片最多的电影
const topMovie = computed(() => {
  return tableData.value[0] || null
})

// 计算前三名排片集中度
const top3Concentration = computed(() => {
  if (!tableData.value.length || !totalShowCount.value) return 0
  const top3Sum = tableData.value.slice(0, 3).reduce((sum, movie) => sum + movie.show_count, 0)
  return (top3Sum / totalShowCount.value) * 100
})

// 模拟排片增长率（实际项目中应从后端获取）
const showCountGrowth = ref(8.5)

// 分析辅助函数
const getTop10Analysis = () => {
  const top10 = tableData.value.slice(0, 10)
  const avgShowCount = top10.reduce((sum, movie) => sum + movie.show_count, 0) / 10
  const aboveAvg = top10.filter(movie => movie.show_count > avgShowCount).length
  return `平均排片 ${Math.round(avgShowCount)} 场，其中 ${aboveAvg} 部影片超过平均水平`
}

const getTrendAnalysis = () => {
  const isRising = showCountGrowth.value > 0
  return isRising ? 
    '整体排片量呈上升趋势，市场活跃度高' : 
    '整体排片量呈下降趋势，市场需要新片提振'
}

const getGrowthComment = () => {
  if (showCountGrowth.value > 15) return '市场表现优异'
  if (showCountGrowth.value > 0) return '市场稳定增长'
  if (showCountGrowth.value > -10) return '市场略有下滑'
  return '市场需要关注'
}

const getTrendComment = () => {
  return showCountGrowth.value > 0 ? 
    '呈现上升态势，影院排片积极性高' : 
    '有所回落，建议关注新片上映情况'
}

const getTop8Proportion = () => {
  if (!tableData.value.length || !totalShowCount.value) return 0
  const top8Sum = tableData.value.slice(0, 8).reduce((sum, movie) => sum + movie.show_count, 0)
  return (top8Sum / totalShowCount.value) * 100
}

const getMarketCompetition = () => {
  const top8Share = getTop8Proportion()
  if (top8Share > 80) return '集中度较高，头部效应明显'
  if (top8Share > 60) return '较为均衡，竞争适度'
  return '分散度高，竞争充分'
}

// 获取进度条颜色
const getProgressColor = (value) => {
  if (value >= 0.3) return '#67C23A'
  if (value >= 0.2) return '#409EFF'
  if (value >= 0.1) return '#E6A23C'
  return '#F56C6C'
}

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 初始化图表
const initChart = () => {
  if (chart.value) {
    chart.value.dispose()
  }
  chart.value = echarts.init(chartRef.value)
}

// 加载数据
const loadData = async () => {
  try {
    console.log('开始加载排片数据...')
    const response = await getMovies()
    console.log('API响应数据:', response)

    if (response?.status === 'success' && response?.data) {
      // 处理电影列表数据
      tableData.value = response.data.map(movie => ({
        ...movie,
        show_count: parseInt(movie.show_count) || 0,
        show_count_rate: parseFloat(movie.show_count_rate.replace('%', '')) / 100 || 0,
        release_info: movie.release_info || '-',
        updated_at: movie.updated_at || '-'
      })).sort((a, b) => b.show_count - a.show_count) // 按排片场次降序排序

      updateChart()
      ElMessage.success('数据加载成功')
    } else {
      console.warn('未获取到有效数据:', response)
      ElMessage.warning('未获取到数据')
      tableData.value = []
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
    tableData.value = []
  }
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 更新图表
const updateChart = () => {
  if (!chart.value || !tableData.value.length) return
  
  let option = {
    title: {
      text: '电影排片分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        if (analysisType.value === 'rate') {
          return `${params[0].name}<br/>排片占比：${(params[0].value * 100).toFixed(2)}%`
        }
        return params.map(param => {
          const value = analysisType.value === 'count' 
            ? param.value + ' 场'
            : (param.value * 100).toFixed(2) + '%'
          return `${param.seriesName}: ${value}`
        }).join('<br/>')
      }
    },
    grid: {
      top: 80,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  }

  switch (analysisType.value) {
    case 'count':
      option = {
        ...option,
        xAxis: {
          type: 'category',
          data: tableData.value.slice(0, 10).map(item => item.movie_name),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '场次'
        },
        series: [{
          name: '排片场次',
          type: 'bar',
          data: tableData.value.slice(0, 10).map(item => item.show_count),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          label: {
            show: true,
            position: 'top'
          }
        }]
      }
      break

    case 'rate':
      option = {
        ...option,
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>排片占比：{d}%'
        },
        series: [{
          name: '排片占比',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '60%'],
          data: tableData.value.slice(0, 8).map(item => ({
            name: item.movie_name,
            value: item.show_count_rate
          })),
          label: {
            show: true,
            formatter: '{b}: {d}%'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      break

    case 'trend':
      const dates = [...new Set(tableData.value.map(item => item.updated_at))].sort()
      const trendData = dates.map(date => {
        const total = tableData.value
          .filter(item => item.updated_at === date)
          .reduce((sum, movie) => sum + movie.show_count, 0)
        return [date, total]
      })

      option = {
        ...option,
        xAxis: {
          type: 'time',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '总场次'
        },
        series: [{
          name: '排片趋势',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          data: trendData,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(58,77,233,0.3)' },
              { offset: 1, color: 'rgba(58,77,233,0.1)' }
            ])
          },
          itemStyle: {
            color: '#3a4de9'
          },
          lineStyle: {
            width: 3
          }
        }]
      }
      break
  }
  
  chart.value.setOption(option)
}

// 监听分析类型变化
watch(analysisType, () => {
  updateChart()
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  chart.value?.resize()
})

onMounted(() => {
  initChart()
  loadData()
})
</script>

<style scoped>
.showing-analysis {
  padding: 20px;
}

.analysis-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 16px;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

.analysis-summary {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.analysis-summary h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

.summary-content {
  color: #606266;
}

.summary-content p {
  margin: 0 0 12px 0;
  font-weight: 500;
}

.summary-content ul {
  margin: 0;
  padding-left: 20px;
}

.summary-content li {
  margin: 8px 0;
  line-height: 1.5;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-progress) {
  margin-right: 0;
  width: 90%;
}

:deep(.el-table .cell) {
  padding: 8px;
}
</style> 